package com.lc.demo.filter;

import com.alibaba.druid.util.StringUtils;
import com.lc.demo.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登陆检查，
 */

@Component
public class LoginHandlerInterceptor implements HandlerInterceptor {
    //目标方法执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 3. 如果是登录请求则放行
        if (request.getRequestURI().contains("/api/auth/login") || request.getRequestURI().contains("/api/auth/register")) {
            return true;
        }
        // 4. 获取请求头
        // 5. 请求头中获取令牌
        String token = request.getHeader("Authorization");
        // 6. 判断请求头中是否有令牌
        if (StringUtils.isEmpty(token)) {
            // 7. 响应中放入返回的状态吗, 没有权限访问
            response.setStatus(401);
            // 8. 返回
            return false;
        }
        //9. 如果请求头中有令牌则解析令牌
        try {
            JwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            //10. 解析jwt令牌出错, 说明令牌过期或者伪造等不合法情 况出现
            response.setStatus(401);
            //11. 返回
            return false;
        }
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
